/* eslint-disable react-hooks/exhaustive-deps */
import { Col, Row, Avatar, Space, message, Switch, Button, Modal } from 'antd'
import React, { createContext, useState } from 'react'
import type { } from '@ant-design/icons';
import { ManOutlined, UserOutlined, WomanOutlined } from '@ant-design/icons';
import styles from './index.less'
import ProCard from '@ant-design/pro-card';
import { ProFormSelect } from '@ant-design/pro-form';
import Overview from './Overview';
import Record, { duanOption } from './Record';
import CourseRecord from './CourseRecord';
import EntryData from './EntryData';
import PlayChess from './PlayChess';
import Emigrated from './Emigrated';
import { getInfoByStepType, getStudentInfo, getUserPointDetail, modifyCryStal, modifyGold, modifyScore, modifyUser } from '@/services/student';
import { getListByUser } from '@/services/student';
import { useEffect } from 'react';
interface PropsPrams {
  idx?: number
  ids?: string[]
  ids3?: string[]
}import { ModalForm, ProFormText } from '@ant-design/pro-form';

import { history } from 'umi';
import WkPlay from './WkPlay';
import { editGokuPower, jumpGrade } from '@/services/goku';
// import Modal from 'antd/lib/modal/Modal';
export const CourseContext = createContext({ courseId: '', uid: '', id: '' });
export default function StudentInfo(props: PropsPrams) {
  const { id } = history.location.query || {};
  const [index, setIndex] = useState<number>();
  const [point, setPoint] = useState<any>();
  const [value1, setValue1] = useState<any>()
  const [value2, setValue2] = useState<any>()
  const [value3, setValue3] = useState<any>()
  const [value4, setValue4] = useState<any>()
  const [courseId, setCourseId] = useState<any>(id);
  const [dataInfo, setDataInfo] = useState<any>();
  const [isshow, setIsshow] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false)
  const [loading, setLoading] = useState<boolean>(false)
  const [isClose, setIsClose] = useState<boolean>(false)
  const [type, setType] = useState<number>()
  const [showModal, setShowModal] = useState<boolean>(false)
  const { idx, ids, ids3 } = props;
  const [tabs, setTabs] = useState<any>([{ key: 'key1', tab: '概览' },
  { key: 'key2', tab: '条目数据' }])


  const [courseCtx, setCourseCtx] = useState({
    uid: ids?.[idx ?? "0"],
    id: ids3?.[idx ?? '0'],
    courseId: courseId,
  })

  useEffect(() => {
    setIndex(idx);
  }, [idx]);
  useEffect(() => {

    if (!ids || index == null) {
      return;
    }
    setCourseCtx({
      uid: ids?.[index ?? 0],
      id: ids3?.[idx ?? '0'],
      courseId: courseId,
    });
    (async () => {
      const res = await getStudentInfo({ id: ids3?.[index] });
      setDataInfo(res.result);
    })();
    (async () => {
      const res = await getUserPointDetail({ param: ids[index] });
      setPoint(res.result);
    })();
    (async () => {
      const res = await getInfoByStepType({ id: courseId });
      setIsshow(res?.result)
      const list = [{ key: 'key1', tab: '概览' },
      { key: 'key2', tab: '条目数据' }]
      if (res?.result?.enableGame == 1) {
        list.push({ key: 'key3', tab: '棋灵对弈' },)
        setTabs(list)
      } else {
        const list1 = list?.filter((item: any) => {
          return item?.key != 'key3'
        })
        setTabs(list1)
      }
      if (res?.result?.passGameFlag == 1) {
        list.push({ key: 'key4', tab: '棋灵闯关' })
        setTabs(list)
      } else {
        const list1 = list?.filter((item: any) => {
          return item?.key != 'key4'
        })
        setTabs(list1)
      }
      if (res?.result?.aiGoFlag == 1) {
        list.push({ key: 'key5', tab: '悟空对弈' },)
        setTabs(list)
      }
      // if (res?.result?.enableAdventure == 1 && res?.result?.enableGame == 1) {
      //   setTabs(
      //     [{ key: 'key1', tab: '概述' },
      //     { key: 'key2', tab: '条目数据' },
      //     { key: 'key3', tab: '棋灵对弈' },
      //     { key: 'key4', tab: '棋灵闯关' },

      //     ]
      //   )
      // }
    })()
  }, [index, courseId]);
  const getInfo = async () => {
    const res1 = await getStudentInfo({ id: ids3![index!] });
    setDataInfo(res1.result);
  }
  const onFinish1 = async (val: any) => {
    setValue2('')
    setValue3('')
    if (type == 1) {
      setLoading(true)
      const res = await modifyUser({ ...val, userId: ids![index!] })
      if (res.success) {
        message.success('编辑姓名成功');
        setVisible(false);
        getInfo()
      }
      setLoading(false)

    } else if (type == 2) {
      setLoading(true)

      const res = await modifyScore({ value: val.value, uid: ids![index!] })
      if (res.success) {
        message.success('编辑对弈积分成功');
        setVisible(false);
        getInfo()
      }
      setLoading(false)

    } else if (type == 3) {
      const res = await modifyGold({ value: val.money, uid: ids![index!] })
      setLoading(true)

      if (res.success) {
        message.success('编辑金币数量成功');
        setVisible(false);
        getInfo()
      }
      setLoading(false)

    } else if (type == 4) {
      const res = await modifyCryStal({ value: val.count, uid: ids![index!] })
      if (res.success) {
        message.success('编辑钻石数量成功');
        setVisible(false);
        getInfo()
      }
    }
    else if (type == 5) {
      setLoading(true)

      const res = await editGokuPower({ value: val.power, uid: ids![index!] })
      if (res.success) {
        message.success('编辑悟空战力成功');
        setVisible(false);
        getInfo()
      }
      setLoading(false)

    }
  }

  const onCancel = () => {
    setVisible(false)
    if (type == 2) {
      setValue1(dataInfo?.playScore)
    }
    if (type == 5) {
      setValue4(dataInfo?.gokuCurPower)
    }
    setValue2('')
    setValue3('')
  }

  const rightTabs = [
    { key: 'tab1', tab: '沟通记录' },
    { key: 'tab2', tab: '报课记录' },
  ]
  const [tab, setTab] = useState('key1');
  const [rightTab, setRightTab] = useState('tab1');
  const showItem = () => {

    if (tab == 'key1') {
      return <Overview />

    } else if (tab == "key2") {
      return <EntryData />
    } else if (tab == "key3") {
      return <PlayChess />;
    } else if (tab == 'key4') {
      return <Emigrated />
    } else if (tab == 'key5') {
      return <WkPlay />
    } else {
      return;
    }
  }
  const showRightItem = () => {
    if (rightTab == 'tab1') {
      return <Record />
    } else {
      return <CourseRecord />;
    }
  }
  const goBack = () => {
    if (!ids || index == null) {
      return;
    }
    setIndex(old => {
      if (index <= 0) {
        return old;
      }
      return old! - 1;
    });
  }
  const goNext = () => {
    if (!ids || index == null) {
      return;
    }
    setIndex(old => {
      if (old! >= ids?.length - 1) {
        return old;
      }
      return old! + 1;
    });

  }
  const handleChange = (e: number) => {
    setTab('key1')
    setCourseId(e)
  }

  const typeOption = (t: string) => {
    if (t == '1') {
      return '长期课'
    } else if (t == '2') {
      return '公开课'
    } else if (t == '3') {
      return '体验课'
    } else if (t == '4') {
      return '录像启蒙课'
    } else if (t == '5') {
      return '录像启蒙课(体验)'
    } else {
      return;
    }
  }
  const stats = (e: any) => {
    if (e == 0) {
      return '未开始';
    } else if (e == 1) {
      return '已开始'
    } else if (e == 2) {
      return '已完成'
    } else if (e == 3) {
      return '已删除'
    } else {
      return ''
    }
  }

  const oninput = (e: any, type1?: number) => {
    if (type1 == 1) {
      setValue1(e.target.value.replace(/[^\d.]/g, ""))
    } else if (type1 == 2) {

      setValue2(e.target.value.replace(/[^\d.]/g, ""))
    }
    else if (type1 == 5) {
      setValue4(e.target.value.replace(/[^\d.]/g, ""))
      if (e.target.value && e.target.value < 1) {
        setValue4(1);
      } else if (e.target.value > 5400) {
        setValue4(5400);
      }
    }
    else {
      setValue3(e.target.value.replace(/[^\d.]/g, ""))
    }
  }
  const onChange = (e: any) => {
    if (e.type == 'click') {
      setValue1('')
      setValue2('')
      setValue3('')
      setValue4('')
    }

  }

  const jumpGroup = async () => {
    setShowModal(false);
    setIsClose(true);
    setLoading(true)
    const res = await jumpGrade({ uid: ids?.[index ?? 0], isGrade: 1 })
    if (res.success) {
      message.success('跳过定级成功');
      const res1 = await getStudentInfo({ id: ids3?.[index ?? 0] });
      setDataInfo(res1.result);
    }
    setLoading(false)

  }
  return (
    <CourseContext.Provider value={courseCtx}>
      <div className={styles.container}>
        <Row className={styles.wrap} style={{ minHeight: "115px" }}>
          <Col className={styles.item_style} span={8}>
            <Row className={styles.info_item} align="middle" justify="center">
              <Avatar size={60} src={dataInfo?.icon} style={{ marginRight: "20px", minHeight: "60px", minWidth: '60px' }} icon={<UserOutlined />} />
              <div className={styles.font_size}>
                <div className={styles.name}>
                  {dataInfo?.nickname || '-'}
                  {
                    dataInfo?.gender == 1 ?
                      <span> <ManOutlined style={{ color: "#169bd5" }} /></span> :
                      <span> <WomanOutlined style={{ color: '#ec808d' }} /></span>
                  }
                </div>
                <Row style={{ flexWrap: 'nowrap' }}>
                  <div>用户ID：{dataInfo?.uid || '-'}</div>
                  <div style={{ marginLeft: "10px" }}>真实姓名：{dataInfo?.realName || '-'}</div>
                  <a style={{ marginLeft: '10px' }} onClick={() => { setVisible(true); setType(1) }}>编辑</a>
                </Row>
                <div>手机号：{dataInfo?.phone || '-'}</div>
                <div style={{ textAlign: 'right' }}>
                  <Space >
                    {
                      index! > 0 ?
                        <a onClick={goBack}>上一条</a> : <span style={{ color: '#ccc' }}>上一条</span>

                    }
                    {
                      index! < ids!.length - 1 ?
                        <a onClick={goNext}>下一条</a> : <span style={{ color: '#ccc' }}>下一条</span>
                    }
                  </Space>
                </div>
              </div>

            </Row>
          </Col>
          {
            isshow?.enableGame == 1 ?
              <Col className={styles.item_style1} id="modal" span={5}>
                <div className={styles.middle_item}>
                  <Row style={{ width: '100%' }}>
                    <div style={{ minWidth: "100px", display: 'flex', justifyContent: 'flex-end' }}>棋士品级：</div>
                    <div>{dataInfo?.playGradeName || '-'}</div>
                  </Row>
                  <Row style={{ width: '100%' }}>
                    <div style={{ minWidth: "100px", display: 'flex', justifyContent: 'flex-end' }}>棋灵对弈积分：</div>
                    <div >{dataInfo?.playScore || '-'}</div>
                    <a style={{ marginLeft: '8px' }} onClick={() => { setVisible(true); setType(2) }}>编辑</a>
                  </Row>
                </div>
              </Col> : null
          }
          <Col className={styles.item_style1} span={5}>
            <div className={styles.middle_item}>
              <Row style={{ width: '100%' }}>
                <div style={{ minWidth: "100px", display: 'flex', justifyContent: 'flex-end' }}>悟空分数：</div>
                <div>{dataInfo?.gokuCurScore || '-'}</div>
              </Row>
              <Row style={{ width: '100%' }}>
                <div style={{ minWidth: "100px", display: 'flex', justifyContent: 'flex-end' }}>悟空战力：</div>
                <div >{dataInfo?.gokuCurPower || '-'}</div>
                <a style={{ marginLeft: '8px' }} onClick={() => { setVisible(true); setType(5) }}>编辑</a>
              </Row>
              <Row style={{ width: '100%' }}>
                <div style={{ minWidth: "100px", display: 'flex', justifyContent: 'flex-end' }}>跳过定级：</div>
                <Switch
                  disabled={dataInfo?.gokuIsGrade == 1 ? true : false}
                  checked={isClose}
                  loading={loading}
                  onChange={(checked) => {
                    if (checked) {
                      setShowModal(checked)
                      setIsClose(checked)
                    } else {
                      setIsClose(checked)
                    }
                  }}
                />

              </Row>
            </div>
          </Col>
          <Col className={styles.item_style1} span={isshow?.enableGame == 1 ? 6 : 8}>
            <div className={styles.middle_item}>
              <Row style={{ width: '100%' }}>
                <div>当前金币数量：</div>
                <div >{dataInfo?.goldCount || '-'}</div>
                <a style={{ marginLeft: '8px' }} onClick={() => { setVisible(true); setType(3) }}>编辑</a>

              </Row>
              <Row style={{ width: '100%' }}>
                <div>当前钻石数量：</div>
                <div>{dataInfo?.crystalCount || '-'}</div>
                <a style={{ marginLeft: '8px' }} onClick={() => { setVisible(true); setType(4) }}>编辑</a>

              </Row>
              <Row style={{ width: '100%' }}>
                <div>当前棋豆数量：</div>
                <div>{point?.currentPoint || '-'}</div>
                <a style={{ marginLeft: '8px', display: 'none' }}>编辑</a>
              </Row>
            </div>
          </Col>
        </Row>
        <Row style={{
          flex: 1, overflowX: 'auto'
        }}>
          <Col span={15} className={styles.form_style}>
            <div className={styles.pro_form_style}>
              <ProFormSelect
                name="select"
                label="课程："
                width="md"
                fieldProps={{
                  onChange: (val) => handleChange(val),
                  allowClear: false,
                  autoFocus: false
                }}
                params={{
                  uid: ids && ids[index!],
                  pageSize: -1
                }}
                initialValue={id}
                placeholder="请选择"
                request={async (params) => {
                  if (!ids || index == null) {
                    return;
                  }
                  const res = await getListByUser({ ...params })
                  return res.result?.records?.map((item: any) => {
                    return { label: `${item.name}-${stats(item.status)} (${duanOption(item.duan)}${item.type ? '/' : ''}${item.type ? typeOption(item.type) : ""}${item.teacherName ? '/' : ""}${item.teacherName || ''})`, value: item.id }
                  })
                }}
              />
            </div>
            <ProCard tabs={{
              tabPosition: 'top',
              activeKey: tab,
              onChange: (key) => {
                setTab(key);
                console.log(key);
              }
            }}>
              {

                tabs?.map((item: any) => {
                  return <ProCard.TabPane key={item.key} tab={item.tab} />

                })
              }
            </ProCard>
            {
              showItem()
            }
          </Col>
          <Col span={9} className={styles.form_style}>
            <ProCard tabs={{
              tabPosition: 'top',
              // activeKey: tab,
              onChange: (key) => {
                setRightTab(key);
              }
            }}>
              {
                rightTabs?.map((item) => {
                  return <ProCard.TabPane key={item.key} tab={item.tab} />
                })
              }
            </ProCard>
            {
              showRightItem()
            }
          </Col>
        </Row>
        <Modal title="跳过定级确认"
          visible={showModal}
          okText="确定"
          cancelText="取消"
          destroyOnClose={true}
          confirmLoading={loading}
          onCancel={() => { setShowModal(false); setIsClose(false) }}
          onOk={jumpGroup}>
          <p>是否跳过悟空定级？</p>
        </Modal>
        <ModalForm

          title={type == 1 ? "编辑真实姓名" : type == 2 ? '编辑对弈积分' : type == 3 ? '编辑金币数量' : '编辑钻石数量'}
          submitter={{
            render: (prop: any) => {
              return [
                <div key="btn">
                  <Button key="back" onClick={onCancel} >
                    取消
                  </Button>,

                  <Button key="submit"
                    disabled={(type == 2 && dataInfo?.playGradeName == null && dataInfo?.playScore == null) || (dataInfo?.gokuIsGrade != 1 && type == 5 && isClose == false) ? true : false}
                    type="primary"
                    loading={loading}
                    onClick={
                      () => { prop?.submit() }
                    }>
                    确定
                  </Button>
                </div>,
                dataInfo?.gokuIsGrade == 1 ? null :
                  type == 5 && isClose == false ?
                    <div key="con" style={{ color: 'red', position: 'absolute', width: "264px", right: 11, bottom: 0 }}>用户未完成悟空定级，不可调整悟空战力</div> : null,

                type == 5 && isClose == false ? <div key="con" style={{ color: 'red', position: 'absolute', width: "264px", right: 11, bottom: 0 }}>用户未完成悟空定级，不可调整悟空战力</div> : null,
                type == 2 && dataInfo?.playGradeName == null && dataInfo?.playScore == null ? <div key="con" style={{ color: 'red', position: 'absolute', width: "268px", right: 11, bottom: 0 }}>用户未完成教学引导棋，不可调整对弈积分</div> : null

              ]
            }
          }}

          modalProps={{
            destroyOnClose: true,
            onCancel: () => setVisible(false)
          }}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          visible={visible}
          onVisibleChange={(val) => {
            setVisible(val)
          }}
          onFinish={onFinish1}
        >
          {
            type == 1 ?
              <ProFormText
                width="md"
                fieldProps={{
                  maxLength: 8,
                }}
                initialValue={dataInfo?.realName}
                name="realName"
                label="真实姓名"
                placeholder="最多输入8个字"
                rules={[{ required: true, message: '请输入8个字以内的真实姓名' },
                {
                  validator: async (_, value) => {
                    if (value && /^[\s]*$/.test(value)) {
                      return Promise.reject(new Error('请输入8个字以内的真实姓名'));
                    } else {
                      return true
                    }
                  }
                }]}
              /> : null
          }
          {
            type == 2 ?
              <ProFormText
                width="md"
                fieldProps={{
                  maxLength: 4,
                  value: value1,
                  onInput: (e) => oninput(e, 1),
                  onChange: (e) => onChange(e)
                }}
                initialValue={dataInfo?.playScore}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                name="value"
                label="对弈积分"
                placeholder="请输入2-5000以内的正整数"
                rules={[
                  { required: true, message: "" },
                  {
                    validator: async (_, value) => {

                      if (value < 2 || value > 5000) {
                        return Promise.reject(new Error('请输入2-5000以内的正整数'));
                      } else if (!(/(^[1-9]\d*$)/.test(value))) {
                        return Promise.reject(new Error('请输入2-5000以内的正整数'));
                      } else {
                        return
                      }
                    },
                  }
                ]}
              /> : null
          }
          {
            type == 3 ?
              <ProFormText
                width="md"
                fieldProps={{
                  maxLength: 4,
                  value: value2,
                  onInput: (e) => oninput(e, 2),
                  onChange: (e) => onChange(e)
                }}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                name="money"
                label="金币数量"
                placeholder="请输入金币数量"
                rules={[{ required: true, message: '' },
                {
                  validator: async (_, value) => {
                    if (value < 1 || value > 5000) {
                      return Promise.reject(new Error('请输入1-5000的金币'));
                    } else if (!(/(^[1-9]\d*$)/.test(value))) {
                      return Promise.reject(new Error('请输入2-5000以内的正整数'));
                    } else {
                      return
                    }
                  },
                }]}
              /> : null
          }
          {
            type == 4 ?
              <ProFormText
                width="md"
                fieldProps={{
                  maxLength: 4,
                  value: value3,
                  onInput: (e) => oninput(e, 3),
                  onChange: (e) => onChange(e)
                }}
                // initialValue={dataInfo?.crystalCount}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                name="count"
                label="钻石数量"
                placeholder="请输入钻石数量"
                rules={[
                  { required: true, message: '' },
                  {
                    validator: async (_, value) => {
                      if (value < 1 || value > 5000) {
                        return Promise.reject(new Error('请输入1-5000的钻石'));
                      } else if (!(/^[1-9]\d*$/.test(value))) {
                        return Promise.reject(new Error('请输入1-5000以内的正整数'));
                      } else {
                        return
                      }
                    },
                  }]}
              /> : null
          }
          {
            type == 5 ?
              <ProFormText
                width="md"
                fieldProps={{
                  value: value4,
                  onInput: (e) => oninput(e, 5),
                  onChange: (e) => onChange(e)
                }}
                initialValue={dataInfo?.gokuCurPower}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                name="power"
                label="悟空战力"
                placeholder="请输入1-5400以内的正整数"
                rules={[
                  { required: true, message: '请输入1-5400以内的正整数' },
                  {
                    validator: async (_, value) => {
                      if (value && !(new RegExp(/^(0?|-?[1-9]\d*)$/).test(value))) {
                        return;
                      } else if (value && value > 5400) {
                        return Promise.reject(new Error('请输入1-5400以内的正整数'));
                      } else {
                        return
                      }
                    },
                  }]}
              /> : null
          }
        </ModalForm>
      </div >
    </CourseContext.Provider >
  )
}
